package cn.wolfcode.crm.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.wolfcode.crm.domain.ProductStock;
import cn.wolfcode.crm.domain.SaleAccount;
import cn.wolfcode.crm.domain.StockOutcomeBill;
import cn.wolfcode.crm.domain.StockOutcomeBillItem;
import cn.wolfcode.crm.mapper.ProductStockMapper;
import cn.wolfcode.crm.mapper.SaleAccountMapper;
import cn.wolfcode.crm.mapper.StockOutcomeBillItemMapper;
import cn.wolfcode.crm.mapper.StockOutcomeBillMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.query.StockOutcomeBillItemQueryObject;
import cn.wolfcode.crm.service.IStockOutcomeBillService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PageUtils;

/**
 * @description
 */

@Service
public class StockOutcomeBillServiceImpl implements IStockOutcomeBillService {

    @Autowired
    private StockOutcomeBillMapper mapper;

    @Autowired
    private StockOutcomeBillItemMapper itemMapper;

    @Autowired
    private ProductStockMapper productStockMapper;

    @Autowired
    private SaleAccountMapper saleAccountMapper;

    @Override
    public void insert(StockOutcomeBill outcomeBill) {
        //保存小票
        mapper.insert(outcomeBill);
        //保存完小票,再保存小票单据明细
        Double discount = outcomeBill.getDiscount();//折扣
        Long billId = outcomeBill.getId();
        String billSn = outcomeBill.getSn();
        List<StockOutcomeBillItem> items = outcomeBill.getItems();
        for (StockOutcomeBillItem item : items) {
            item.setDiscount(discount);
            item.setBillId(billId);
            item.setBillSn(billSn);

            BigDecimal amount = item.getSalePrice().multiply(item.getNumber())
                    .multiply(new BigDecimal(item.getDiscount()))
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            item.setAmount(amount);//折扣后单品总金额
            item.setItemStatus(1);
            itemMapper.insert(item);
        }

        //更新库存
        for (StockOutcomeBillItem item : items) {
            ProductStock ps =productStockMapper.selectByDepotIdAndProductId(
            		outcomeBill.getDepot().getId(),item.getProduct().getId());          
            BigDecimal storeNumber = ps.getStoreNumber();
            BigDecimal saleNumber = item.getNumber();
            ps.setStoreNumber(storeNumber.subtract(saleNumber));
            ps.setAmount(ps.getPrice().multiply(storeNumber.subtract(saleNumber)));
            productStockMapper.updateByPrimaryKey(ps);
        }


        // TODO: 2018/7/14  记录销售帐,直接更改库存(有商品卖肯定有库存,这里不再判断库存)
        //库存更新完毕后需要更新销售利润报表
        for (StockOutcomeBillItem item : items) {
            //
            ProductStock ps = productStockMapper.selectByDepotIdAndProductId(1L,item.getProduct().getId());
            SaleAccount sa = new SaleAccount();
            sa.setInputTime(outcomeBill.getInputTime());
            sa.setNumber(item.getNumber());
            sa.setCostPrice(ps.getPrice());
            sa.setCostAmount(ps.getPrice().multiply(item.getNumber()));
            sa.setSalePrice(item.getSalePrice());
            sa.setSaleAmount(item.getSalePrice().multiply(item.getNumber()));
            sa.setProductId(item.getProduct().getId());
            sa.setSalemanId(outcomeBill.getOperator().getId());
            sa.setClientId(outcomeBill.getMember().getId());
            sa.setBillId(outcomeBill.getId());
            saleAccountMapper.insert(sa);
        }

    }


    @Override
    public StockOutcomeBill selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<StockOutcomeBill> selectAll() {
        return mapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        return PageUtils.query(qo, mapper);
    }

    public PageResult queryBillItemByBillId(Long billId) {
        StockOutcomeBillItemQueryObject qo = new StockOutcomeBillItemQueryObject();
        qo.setBillId(billId);

        return PageUtils.query(qo, itemMapper);
    }

    /**
     * 根据小票id和itemId执行退货(只有小票id为整单退货,只有itemId为部分退货)
     *
     * @param billId
     * @param itemId
     */
    public void saleReturn(Long billId, Long itemId) {
        if (billId != null && itemId == null) {
            //整单退货,改变小票的状态为2
            mapper.saleBillReturn(billId);
            //退整张单的明细
            itemMapper.saleItemReturnByBillId(billId);
            //删除销售帐记录,通过小票id 整个更改状态
            saleAccountMapper.updateStatusByBillIdAndProductId(billId,null);


            //增加库存
            StockOutcomeBill returnBill = mapper.selectByPrimaryKey(billId);
            List<StockOutcomeBillItem> items = returnBill.getItems();
            for (StockOutcomeBillItem item : items) {
                ProductStock ps =productStockMapper.selectByDepotIdAndProductId(1L,item.getProduct().getId());//写死,默认就是本店
                BigDecimal storeNumber = ps.getStoreNumber();
                BigDecimal saleNumber = item.getNumber();
                ps.setStoreNumber(storeNumber.add(saleNumber));
                ps.setAmount(ps.getPrice().multiply(storeNumber.add(saleNumber)));
                productStockMapper.updateByPrimaryKey(ps);
            }

        } else if (billId != null && itemId != null) {
            //部分退货,改变对应明细表中的该条明细状态为2
            itemMapper.saleItemReturn(billId,itemId);

            //变更销售帐记录状态为2,通过小票id和该退货商品id
            StockOutcomeBillItem item = itemMapper.selectByPrimaryKey(itemId);
            saleAccountMapper.updateStatusByBillIdAndProductId(billId,item.getProduct().getId());

            //需要判断,如果小票下的所有明细都被退货,则小票也就退单了
            List<StockOutcomeBillItem> list = itemMapper.selectByBillId(billId);
            if (list.size()==0){
                mapper.saleBillReturn(billId);
            }

            //再增加库存
            ProductStock ps =productStockMapper.selectByDepotIdAndProductId(1L,item.getProduct().getId());
            BigDecimal storeNumber = ps.getStoreNumber();
            BigDecimal saleNumber = item.getNumber();
            ps.setStoreNumber(storeNumber.add(saleNumber));
            ps.setAmount(ps.getPrice().multiply(storeNumber.add(saleNumber)));
            productStockMapper.updateByPrimaryKey(ps);

        }
    }
























   /* public void audit(Long id) {
        StockOutcomeBill oldBill = mapper.selectByPrimaryKey(id);
        //审核出库单,就是改变状态,审核人和审核时间
        if (oldBill.getStatus() == StockOutcomeBill.STATUS_NORMAL) {
            oldBill.setStatus(StockOutcomeBill.STATUS_AUDITED);
            oldBill.setAuditTime(new Date());
            oldBill.setAuditor(UserContext.getUserFromSession());
            mapper.audit(oldBill);
        }

        //出库单审核时,需要查询对应明细商品的库存信息看是否能满足发货要求,更新库存
        Long depotId = oldBill.getDepot().getId();
        List<StockOutcomeBillItem> items = oldBill.getItems();

        for (StockOutcomeBillItem item : items) {
            ProductStock ps = productStockMapper.selectByProductIdAndDepotId(item.getProduct().getId(), depotId);
            String productName = item.getProduct().getName();
            BigDecimal saleNumber = item.getNumber();
            //没货
            if (ps==null){
                throw new LogicException("["+ oldBill.getDepot().getName() +"]中,"+"["+ productName +"]暂时缺货!");
            }
            //库存不足
            BigDecimal storeNumber = ps.getStoreNumber();
            if (storeNumber.compareTo(saleNumber) < 0 ){
                throw new LogicException("["+ oldBill.getDepot().getName() +"]中,"+"["+ productName +"]库存仅剩["+ storeNumber +"],不足["+ saleNumber +"]");
            }
            //满足发货要求,修改库存,修改库存总价
            ps.setStoreNumber(storeNumber.subtract(saleNumber));
            ps.setAmount(ps.getPrice().multiply(storeNumber.subtract(saleNumber)));
            productStockMapper.updateByProductIdAndDepotId(ps);
        }

        //库存更新完毕后需要更新销售利润报表
        for (StockOutcomeBillItem item : items) {
            //
            ProductStock ps = productStockMapper.selectByProductIdAndDepotId(item.getProduct().getId(), depotId);
            SaleAccount sa = new SaleAccount();
            sa.setVdate(oldBill.getVdate());
            sa.setNumber(item.getNumber());
            sa.setCostPrice(ps.getPrice());
            sa.setCostAmount(ps.getPrice().multiply(item.getNumber()));
            sa.setSalePrice(item.getSalePrice());
            sa.setSaleAmount(item.getSalePrice().multiply(item.getNumber()));
            sa.setProductId(ps.getProductId());
            sa.setSalemanId(oldBill.getInputUser().getId());
            sa.setClientId(oldBill.getClient().getId());
            sa.setBillId(oldBill.getId());
            saleAccountMapper.insert(sa);
        }

    }*/

}
